import LogManager from '@utils/LogManager';

/**
 * 悬浮窗管理器
 */
class FloatyManager {
  private window: any = null;
  private logWindow: any = null;
  private isRunning: boolean = false;
  private count: number = 0;
  private onStateChange: ((running: boolean) => void) | null = null;

  checkPermission(): boolean {
    try {
      // 检查是否已经获取了悬浮窗权限
      let hasPermission = false;
      if (device.sdkInt >= 23) {
        hasPermission = Settings.canDrawOverlays(context);
      } else {
        hasPermission = true;
      }

      if (!hasPermission) {
        // 打开悬浮窗权限设置页面
        app.startActivity({
          action: 'android.settings.action.MANAGE_OVERLAY_PERMISSION',
          data: 'package:' + context.getPackageName(),
        });
        return false;
      }
      return true;
    } catch (e: unknown) {
      if (e instanceof Error) {
        LogManager.error('检查悬浮窗权限失败: ' + e.message);
      }
      return false;
    }
  }

  show(): void {
    if (this.window) return;

    try {
      // 检查悬浮窗权限
      if (!this.checkPermission()) {
        LogManager.error('请先授予悬浮窗权限');
        return;
      }

      // 创建主悬浮窗
      this.window = floaty.window(
        `<frame id="main" w="auto" h="auto" gravity="center">
                    <card w="160" h="48" cardCornerRadius="24dp" cardElevation="4dp" bg="#FFFFFF" clickable="true">
                        <horizontal padding="8" gravity="center">
                            <text id="status" text="已停止" textColor="#666666" layout_weight="1" gravity="center"/>
                            <button id="toggleBtn" text="开始" style="Widget.AppCompat.Button.Borderless" textColor="#4CAF50" w="48dp" h="32dp" textSize="12sp"/>
                        </horizontal>
                    </card>
                </frame>`,
      );

      // 创建日志悬浮窗
      this.logWindow = floaty.window(
        `<frame id="log" w="auto" h="auto" gravity="center">
                    <card w="240" h="160" cardCornerRadius="16dp" cardElevation="4dp" bg="#FFFFFF">
                        <vertical padding="12">
                            <horizontal>
                                <text text="运行日志" textColor="#000000" textSize="14sp" textStyle="bold" layout_weight="1"/>
                                <text id="count" text="已抢到: 0" textColor="#666666" textSize="12sp"/>
                            </horizontal>
                            <scroll w="*" h="*" marginTop="8">
                                <text id="logText" text="" textColor="#666666" textSize="12sp" w="*"/>
                            </scroll>
                        </vertical>
                    </card>
                </frame>`,
      );

      // 设置主悬浮窗位置
      this.window.setPosition(device.width - 200, device.height / 2);

      // 设置日志悬浮窗位置
      this.logWindow.setPosition(device.width - 280, device.height / 2 + 100);

      // 设置主悬浮窗可拖动
      let mainTouchX = 0;
      let mainTouchY = 0;
      let mainWindowX = 0;
      let mainWindowY = 0;
      const that = this;

      this.window.main.setOnTouchListener(function (view: any, event: any) {
        switch (event.getAction()) {
          case event.ACTION_DOWN:
            mainTouchX = event.getRawX();
            mainTouchY = event.getRawY();
            mainWindowX = that.window.getX();
            mainWindowY = that.window.getY();
            return true;
          case event.ACTION_MOVE:
            that.window.setPosition(mainWindowX + (event.getRawX() - mainTouchX), mainWindowY + (event.getRawY() - mainTouchY));
            return true;
        }
        return false;
      });

      // 设置日志悬浮窗可拖动
      let logTouchX = 0;
      let logTouchY = 0;
      let logWindowX = 0;
      let logWindowY = 0;

      this.logWindow.log.setOnTouchListener(function (view: any, event: any) {
        switch (event.getAction()) {
          case event.ACTION_DOWN:
            logTouchX = event.getRawX();
            logTouchY = event.getRawY();
            logWindowX = that.logWindow.getX();
            logWindowY = that.logWindow.getY();
            return true;
          case event.ACTION_MOVE:
            that.logWindow.setPosition(logWindowX + (event.getRawX() - logTouchX), logWindowY + (event.getRawY() - logTouchY));
            return true;
        }
        return false;
      });

      // 绑定按钮事件
      this.window.toggleBtn.click(() => {
        try {
          this.isRunning = !this.isRunning;
          this.setRunningState(this.isRunning);
          if (this.onStateChange) {
            this.onStateChange(this.isRunning);
          }
          LogManager.info(this.isRunning ? '任务已启动' : '任务已停止');
        } catch (e: unknown) {
          if (e instanceof Error) {
            LogManager.error('处理按钮点击事件失败: ' + e.message);
          }
        }
      });

      LogManager.info('悬浮窗已显示');
    } catch (e: unknown) {
      if (e instanceof Error) {
        LogManager.error('创建悬浮窗失败: ' + e.message);
      }
    }
  }

  hide(): void {
    try {
      if (this.window) {
        this.window.close();
        this.window = null;
      }
      if (this.logWindow) {
        this.logWindow.close();
        this.logWindow = null;
      }
      LogManager.info('悬浮窗已隐藏');
    } catch (e: unknown) {
      if (e instanceof Error) {
        LogManager.error('关闭悬浮窗失败: ' + e.message);
      }
    }
  }

  setRunningState(running: boolean): void {
    try {
      if (!this.window) return;

      this.isRunning = running;
      const status = this.window.status;
      const toggleBtn = this.window.toggleBtn;

      if (running) {
        status.setText('运行中');
        status.setTextColor(android.graphics.Color.parseColor('#4CAF50'));
        toggleBtn.setText('停止');
        toggleBtn.setTextColor(android.graphics.Color.parseColor('#F44336'));
      } else {
        status.setText('已停止');
        status.setTextColor(android.graphics.Color.parseColor('#666666'));
        toggleBtn.setText('开始');
        toggleBtn.setTextColor(android.graphics.Color.parseColor('#4CAF50'));
      }
    } catch (e: unknown) {
      if (e instanceof Error) {
        LogManager.error('更新悬浮窗状态失败: ' + e.message);
      }
    }
  }

  updateStatus(text: string): void {
    try {
      if (this.window && this.window.status) {
        this.window.status.setText(text);
      }
    } catch (e: unknown) {
      if (e instanceof Error) {
        LogManager.error('更新悬浮窗状态文本失败: ' + e.message);
      }
    }
  }

  updateCount(count: number): void {
    try {
      if (this.logWindow && this.logWindow.count) {
        this.count = count;
        this.logWindow.count.setText(`已抢到: ${count}`);
      }
    } catch (e: unknown) {
      if (e instanceof Error) {
        LogManager.error('更新悬浮窗计数失败: ' + e.message);
      }
    }
  }

  addLog(message: string): void {
    try {
      if (this.logWindow && this.logWindow.logText) {
        const timestamp = new Date().toLocaleTimeString();
        const log = `[${timestamp}] ${message}`;
        const currentText = this.logWindow.logText.getText().toString();
        const logs = currentText ? currentText.split('\n') : [];
        logs.push(log);
        if (logs.length > 100) {
          logs.shift();
        }
        this.logWindow.logText.setText(logs.join('\n'));
      }
    } catch (e: unknown) {
      if (e instanceof Error) {
        LogManager.error('更新悬浮窗日志失败: ' + e.message);
      }
    }
  }

  setOnStateChangeListener(callback: (running: boolean) => void): void {
    this.onStateChange = callback;
  }

  isTaskRunning(): boolean {
    return this.isRunning;
  }

  isShowing(): boolean {
    return this.window !== null && this.logWindow !== null;
  }
}

// 创建单例实例
const floatyManager = new FloatyManager();
export default floatyManager;
